﻿Imports System.Xml.Serialization
Imports System.Text.RegularExpressions

Public Class ReWriteConfig
    Inherits DefaultConfig
    Private Shared mConfigInfo As RewriterRuleCollection
    Private Shared mConfigFilePath As String
    Private Shared mFileDateTime As DateTime

    REM 配置文件路径
    Public Overloads Shared ReadOnly Property ConfigFilePath() As String
        Get
            If String.IsNullOrEmpty(mConfigFilePath) OrElse Not IO.File.Exists(mConfigFilePath) Then
                Dim Path As String = AppSettings("ConfigPath")
                If Not Path.EndsWith("/") Then Path = String.Concat(Path, "/")
                mConfigFilePath = System.Web.HttpContext.Current.Server.MapPath(String.Format("{0}Rewriter.config", Path))
            End If
            Return mConfigFilePath
        End Get
    End Property

    Public Shared Function Load() As RewriterRuleCollection
        mErrMessage = Nothing
        Try
            If mConfigInfo Is Nothing Then mConfigInfo = New RewriterRuleCollection
            mConfigInfo = CType(LoadConfig(mFileDateTime, ConfigFilePath, mConfigInfo), RewriterRuleCollection)
        Catch ex As Exception
            mErrMessage = ex.Message
        End Try
        Return mConfigInfo
    End Function

End Class

<Serializable()> <XmlRoot("Rules")> Public Class RewriterRuleCollection
    Implements IConfigInfo
    Public DefaultSendTo As String
    Private sUrl, sUrlHost As String
    <XmlElement("RewriterRule")> Public Items() As RewriterRule

    REM 查找数组
    Public Function Find(ByVal url As String, ByVal urlhost As String) As RewriterRule
        sUrl = url
        sUrlHost = urlhost
        If Items Is Nothing OrElse Items.Length = 0 Then Return Nothing
        Return Array.Find(Items, AddressOf FindWhere)
    End Function

    Private Function FindWhere(ByVal item As RewriterRule) As Boolean
        Dim LookFor As String
        If sUrl.StartsWith("http://") AndAlso Not item.LookFor.StartsWith("http://") Then
            LookFor = String.Concat("http://", sUrlHost, item.LookFor)
        Else
            LookFor = item.LookFor
        End If
        Return Regex.IsMatch(sUrl, String.Concat("^", LookFor, "$"), RegexOptions.IgnoreCase)
    End Function
End Class


<Serializable()> Public Class RewriterRule
    Public LookFor As String
    Public SendTo As String
    Public Page As String
End Class




